﻿using B.S.BasicData.Api.Read.Application.Command.Menu;
using B.S.BasicData.Domian.Entities.Menu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.Menu
{
    public class DelMenuHandler:IRequestHandler<DelMenuCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;

        public DelMenuHandler(IBaseRepository<MenuModel>menuRepo)
        {
            this.menuRepo = menuRepo;
        }

        public async Task<ApiResult<int>> Handle(DelMenuCommand request, CancellationToken cancellationToken)
        {
            var res=new ApiResult<int>();
            var menu=menuRepo.GetAll().ToList();
            var count = await Del(request.Id, menu);

            if(count>0)
            {
                res.Message = "删除成功";
                res.Code = ApiEnum.Ok;
            }
            else
            {
                res.Message = "删除失败";
                res.Code = ApiEnum.File;
            }
            res.Data = count;
            return await Task.FromResult(res);

        }

        public async  Task<int> Del(int id,List<MenuModel>ids)
        {
            int count = 0;
            var resl= ids.FirstOrDefault(x=>x.Id==id);
            if(resl != null && !resl.IsDel)
            {
                resl.IsDel = true;
                menuRepo.Update(resl);
                count++;
                var meunmodel=ids.Where(x=>x.Pid==id &&!x.IsDel).ToList();
                foreach(var item in meunmodel)
                {
                    count += await Del(item.Id, ids);
                }
            }
            return count;
        }
    }
}
